package org.example.foodhealth.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.example.foodhealth.bean.UserProfile;
import org.example.foodhealth.config.JwtTokenUtils;
import org.example.foodhealth.repository.UserProfileRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/UserProfile")
public class UserProfileController {
    private final UserProfileRepository userProfileRepository;

    public UserProfileController(UserProfileRepository userProfileRepository) {
        this.userProfileRepository = userProfileRepository;
    }

    //编辑资料
    @PostMapping("/edit")
    public ResponseEntity<?> editProfile(@RequestBody Map<String, Object> updates, HttpServletRequest request) {
        Long userId = JwtTokenUtils.getUserIdFromRequest(request); // 解析 JWT，获取 userId
        if (userId == null) {
            return ResponseEntity.status(401).body(Map.of("error", "未授权"));
        }

        Optional<UserProfile> userProfileOpt = userProfileRepository.findByUserId(userId);
        if (userProfileOpt.isEmpty()) {
            return ResponseEntity.status(404).body(Map.of("error", "用户资料未找到"));
        }

        UserProfile userProfile = userProfileOpt.get();
        updates.forEach((key, value) -> {
            switch (key) {
                case "avatar": userProfile.setAvatar(value.toString()); break;
                case "name": userProfile.setName(value.toString()); break;
                case "gender":
                    String gender = value.toString();
                    if (!gender.equals("Male") && !gender.equals("Female") && !gender.equals("Other")) return;
                    userProfile.setGender(gender);
                    break;
                case "age": userProfile.setAge(Integer.parseInt(value.toString())); break;
            }
        });

        userProfileRepository.save(userProfile);
        return ResponseEntity.ok(Map.of("message", "资料更新成功"));
    }
}
